package com.example.testng.utils;

import java.sql.*;

/**
 *  数据库操作工具类
 */
public class DatabaseUtil {


    private static final String URL = "jdbc:mysql://localhost:3306/testng_demo";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    private static Connection connection;

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("MySQL JDBC Driver not found", e);
        }
    }

    /**
     * 获取数据库连接
     * @return 数据库连接对象
     * @throws SQLException 如果连接失败
     */
    public static Connection getConnection() throws SQLException {
        if (connection == null || connection.isClosed()) {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        }
        return connection;
    }

    /**
     * 执行查询语句
     * @param query SQL查询语句
     * @return 查询结果集
     * @throws SQLException 如果查询执行失败
     */
    public static ResultSet executeQuery(String query) throws SQLException {
        Connection conn = getConnection();
        Statement stmt = conn.createStatement();
        return stmt.executeQuery(query);
    }

    /**
     * 执行更新语句（INSERT、UPDATE、DELETE）
     * @param query SQL更新语句
     * @return 受影响的行数
     * @throws SQLException 如果更新执行失败
     */
    public static int executeUpdate(String query) throws SQLException {
        Connection conn = getConnection();
        Statement stmt = conn.createStatement();
        return stmt.executeUpdate(query);
    }

    /**
     * 关闭数据库连接
     */
    public static void closeConnection() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}